package com.example.config;

import com.example.annotation.UserAuth;
import com.example.cache.CaffineCache;
import com.example.swagger.GlobalResultEnum;
import com.example.tools.ApiResult;
import com.example.tools.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author liheng
 * 用户认证拦截器
 */
@Slf4j
@Component
public class UserAuthInterceptor implements HandlerInterceptor {
    private final CaffineCache<String> accessTokenCache;
    public final static String SYS_TOKEN = "token";

    @Autowired
    public UserAuthInterceptor(CaffineCache<String> accessTokenCache) {
        this.accessTokenCache = accessTokenCache;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 类级拦截标记
            UserAuth userAuthentication = handlerMethod.getBeanType().getAnnotation(UserAuth.class);
            if (!Objects.isNull(userAuthentication)) {
                String token = request.getHeader(SYS_TOKEN);
                if (!StringUtils.hasLength(token)) {
                    ResponseUtils.renderJson(response, ApiResult.status(GlobalResultEnum.TOKEN_EXPIRE));
                    return false;
                } else {
                    String userInfo = accessTokenCache.getKey(token);
                    if (!StringUtils.hasLength(userInfo)) {
                        ResponseUtils.renderJson(response, ApiResult.status(GlobalResultEnum.TOKEN_EXPIRE));
                        return false;
                    } else {
                        return true;
                    }
                }
            }
        }
        return true;
    }
}
